<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { RouterView ,useRouter, useRoute} from 'vue-router'
import GetFriend from '@/component/createroom/getfriend.vue'
import InviteWindows from '@/component/invite-windows.vue'
import ws from '@/services/websocket'
import { useUserStore } from '@/stores/user'
import { useRoomStore } from '@/stores/room'
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const roomStore = useRoomStore()
const showRight = ref(false)
const rightVal = ref(null)
//监听函数，用户点击了邀请好友，打开其他组建
function onSlotClick(val){
  rightVal.value = val
  showRight.value = true
}
//点击了返回就要收起全部的页面。
async function goBack() {
  try { await click.play() } catch (_) {}
  // 如果当前在 /pre-create-room/choose-friend-2v2 子路由，发送离开消息
  try {
    if (route.path === '/pre-create-room/choose-friend-2v2') {
      const payload = {
        genre: 3,
        type: 'hasleft',
        uid: userStore.uid,
        rid: roomStore.room_id,
      }
      ws.send(JSON.stringify(payload))
      console.log('已发送离开房间：', payload)
    }
  } catch (e) {
    console.error('发送离开房间失败：', e)
  }
  showRight.value = false
  rightVal.value = null
  router.back()
}

// 被邀请提示数据
const showInvite = ref(false)
const inviteNickname = ref('')
const inviteFromUid = ref('')
const inviteRoomId = ref('')
const invitePos = ref(null)
//被邀请回调函数
function handleBeInvited(message){
  // 期望：{ genre:3, type:'beinvited', nickname, from_uid, rid, pos }
  inviteNickname.value = message?.nickname || ''
  inviteFromUid.value = message?.from_uid || ''
  inviteRoomId.value = message?.rid || ''
  invitePos.value = message?.pos ?? null
  showInvite.value = true
}
// 马上要跳转到房间页面了，正在接受
function handleHasInvited(message){
  console.log('hasinvited 消息：', message)
  // 带上房间玩家数据（players）与 invited2v2 模式，以及 position 与 rid
  const roomData = encodeURIComponent(JSON.stringify(message?.players ?? []))
  const position = message?.position ?? message?.pos ?? ''
  const rid = message?.rid ?? ''
  router.push({ path: '/pre-create-room/choose-friend-2v2', query: { model: 'invited2v2', room_data: roomData, position, rid } })
}
//接受了邀请
function acceptInvite(){
  showInvite.value = false
  try {
    const payload = {
      genre: 3,
      type: 'hasinvited',
      rid: inviteRoomId.value,
      uid: userStore.uid,
      nickname: userStore.nickename,
      reply: 1,
      fromuid: inviteFromUid.value,
      profile: userStore.profile,
      position: invitePos.value
    }
    ws.send(JSON.stringify(payload))
    console.log('已发送同意邀请：', payload)
  } catch (e) {
    console.error('发送同意邀请失败：', e)
  }
}
//拒绝了邀请
function rejectInvite(){
  showInvite.value = false
}

onMounted(() => {
  ws.on(3, 'beinvited', handleBeInvited)
  ws.on(3, 'hasinvited', handleHasInvited)
})

onBeforeUnmount(() => {
  ws.off(3, 'beinvited')
  ws.off(3, 'hasinvited')
})

</script>

<template>
  <div class="pre-create-room">
    <div class="inner">
      <div class="left">
        <button class="back-btn" @click="goBack">返回</button>
      </div>
      <div class="center">
        <RouterView v-slot="{ Component }">
          <component :is="Component" @slot-click="onSlotClick" />
        </RouterView>
      </div>
      <div class="right">
        <!-- 这里如果点击了收起，则要收起全部的页面。监听collapse事件。 -->
        <GetFriend v-if="showRight" :slot-index="rightVal" @collapse="showRight = false" />
      </div>
    </div>

    <!-- 被邀请提示（右下角，非强制） -->
    <InviteWindows
      v-if="showInvite"
      :nickname="inviteNickname"
      :rid="inviteRoomId"
      :pos="invitePos"
      :duration="30"
      @accept="acceptInvite"
      @reject="rejectInvite"
      @close="rejectInvite"
    />
  </div>
  
</template>

<style scoped>
.pre-create-room {
  position: relative;
  min-height: 100vh;
  width: 100%;
  background: url('http://117.72.17.45:5500/data/bks/bk1.jpg') center/cover no-repeat fixed;
}
.inner {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: stretch;
  gap: 12px;
  padding: 12px 16px;
  box-sizing: border-box;
}
.left { flex: 0 0 25%; position: relative; }
.center { flex: 0 0 50%; display: flex; align-items: center; justify-content: center; }
.right { flex: 0 0 25%; }
.back-btn {
  position: absolute;
  top: 12px;
  left: 16px;
  padding: 16px 24px;
  background: rgba(255,255,255,0.9);
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-size: 20px;
}
</style>


